package com.hencoderplus.demo1;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * hencoderplus
 * Created by lzw on 2018/10/23. 14:18:30
 * 邮箱：632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class PieChart extends View {

    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    public static final int PULLED_OUT_INDEX = 2;
    RectF bound = new RectF();
    public static final int RADIUS = (int) Utils.dp2Px(100);

    private int currentAngel = 0;

    int[] angels = new int[]{60,100,120,80};
    int[] colors = new int[]{Color.parseColor("#2979ff"),
            Color.parseColor("#c2185b"),
            Color.parseColor("#009688"),
            Color.parseColor("#ff8f00")};
    private double LENGTH = 20;

    {

        bound.set(getWidth()/2-RADIUS,getHeight()/2-RADIUS,getWidth()/2+RADIUS,
                getHeight()/2+RADIUS);
    }

    public PieChart(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    //如果在这个地方进行  bound.set(getWidth()/2-RADIUS,getHeight()/2-RADIUS,getWidth()/2+RADIUS,
    // getHeight()/2+RADIUS);
    //会以window左上角为原点，因为这个时候还没进行layout，所以应该在onSIzeChange方法里设置

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        bound.set(getWidth()/2-RADIUS,getHeight()/2-RADIUS,getWidth()/2+RADIUS,
                getHeight()/2+RADIUS);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < colors.length; i++) {
            paint.setColor(colors[i]);
            canvas.save();
            if (i == PULLED_OUT_INDEX){
                canvas.translate((float)(Math.cos(Math.toRadians(angels[i]/2+currentAngel))*LENGTH),
                        (float) (Math.sin(Math.toRadians(currentAngel+angels[i]/2))*LENGTH));
            }

            canvas.drawArc(bound,currentAngel,angels[i],true,paint);
            canvas.restore();
            currentAngel += angels[i];
        }
    }
}
